package com.fy.service.server.channel;



import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

@Component
public class SocketChannelInitializer extends ChannelInitializer<Channel> {

    @Autowired
    private SimpleChannelInboundHandler socketServerBusiHandler;

    @Override
    protected void initChannel(Channel ch) throws Exception {

        //每一个Channel 都有一个ChannelPipeline  用来处理配置的Handler
        //Handler 分为 InboundHandler 和 OutboundHandler, InboundHandler顺序执行，OutboundHandler逆序执行。
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
        pipeline.addLast("decoder", new StringDecoder(Charset.forName("UTF-8")));
        pipeline.addLast("encoder", new StringEncoder(Charset.forName("UTF-8")));
        //闲置事件管理器 多长时间未收到客户端发来的数据就会触发userEventTriggered  事件
        pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
        pipeline.addLast("socketServerBusiHandler", socketServerBusiHandler);


    }

}